const React = require('react');
const {
  View,
  ListView,
  StyleSheet,
  Animated
} = require('react-native');
const {
  JDScrollView,
  JDText,
  JDRouter,
  JDButton,
  JDTouchable,
  JDScrollTop
} = require('@areslabs/jdreact-core-lib');
const { NavigationBar } = JDRouter;

function getMockData() {
  let result = [];
  for(let i = 0; i < 100; i++) {
    result.push(`Hello ${parseInt(Math.random() * 10000)}`);
  }
  return result;
}

class PullListView extends React.Component {
  constructor(props) {
    super(props);
    this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

    this.state = {
      isRefreshing: false,
      listData: getMockData(),
    };
    this.scrollY = new Animated.Value(0);
  }

  render() {
    return (
      <View style={styles.wrapper}>
        <NavigationBar Title="ListView" />
        <ListView
          style={styles.wrapper}
          contentContainerStyle={styles.contentContainerStyle}
          dataSource={this.ds.cloneWithRows(this.state.listData)}
          renderRow={this._renderRow}
          refreshing={this.state.isRefreshing}
          onRefresh={() => { this.onRefresh(); }}
          initialListSize={5}
          pageSize={5}
          ref={v=>this.listview=v}
          onScroll={(e)=>{
              this.scrollY.setValue(e.nativeEvent.contentOffset.y);
          }}
          renderScrollComponent={(props) => (<JDScrollView {...props} />)}
        />
        <JDScrollTop scrollY={this.scrollY} onPress={this.scrollTop}/>
      </View>
    );
  }
  scrollTop = () => {
      this.listview.scrollTo({ x: 0, y: 0, animated: true });
  }
  _renderRow = (rowData) => {
     return (
      <JDTouchable contentContainerStyle={styles.row} onPress={() => { alert(rowData); }}>
        <JDText>{rowData}</JDText>
      </JDTouchable>
    );
  };

  onRefresh = () => {
    this.setState({
      isRefreshing: true,
    });
    setTimeout(() => {
        this.setState({
          isRefreshing: false,
          listData: getMockData()
        });
    }, 3000);
  };
}

const styles = StyleSheet.create({
  wrapper: {
    flex: 1,
  },
  contentContainerStyle: {
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
  },
  row: {
      height: 100,
      borderColor: '#F00',
      borderWidth: 1,
      marginVertical: 10,
  }
});

module.exports = PullListView;
